package com.mk.admin.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.mk.admin.mapper.PatientCardMapper;
import com.mk.admin.model.ResultDto;
import com.mk.admin.model.dto.EHCDto;
import com.mk.admin.model.dto.PatientCardDto;
import com.mk.admin.model.dto.PatientSelectDto;
import com.mk.admin.model.entity.PatientCardEntity;
import com.mk.admin.model.query.PatientCardHeathCardQuery;
import com.mk.admin.model.query.PatientSelectQuery;
import com.mk.admin.model.vo.*;
import com.mk.admin.service.PatientCardService;
import com.mk.admin.util.HttpTool;
import com.mk.admin.util.JSONCopy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;

@Service
public class PatientCardServiceImpl implements PatientCardService {
    @Autowired
    private PatientCardMapper patientCardMapper;
    private final String defaultOpenId = "o2lnx6pKPgLk-vfGCPDHjvzL9EYU";

    @Override
    public ResultDto select(PatientCardVo patientCardVo) {
//        IPage<PatientCardEntity> iPage = new Page<>(patientCardVo.getPage(), patientCardVo.getSize());
//        LambdaQueryWrapper<PatientCardEntity> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(PatientCardEntity::getPatName, patientCardVo.getPatName());
//        queryWrapper.eq(PatientCardEntity::getPatId, patientCardVo.getPatId());
//        queryWrapper.like(PatientCardEntity::getProvince, patientCardVo.getProvince());
//        queryWrapper.like(PatientCardEntity::getCity, patientCardVo.getCity());
//        queryWrapper.like(PatientCardEntity::getDistrict, patientCardVo.getDistrict());
//        queryWrapper.eq(PatientCardEntity::getLoginStatus, patientCardVo.getLoginStatus());
//        queryWrapper.eq(PatientCardEntity::getStatus, patientCardVo.getStatus());
//        queryWrapper.eq(PatientCardEntity::getOpenId, patientCardVo.getOpenId());
//        return ResultDto.data(patientCardMapper.selectPage(iPage, queryWrapper));
        PatientCardEntity entity = JSONCopy.copy(patientCardVo, PatientCardEntity.class);
        return ResultDto.data(patientCardMapper.count(entity), patientCardMapper.select(entity));
    }

    @Override
    public ResultDto healthCardList(PatientCardHeathCardQuery query) {
        List<PatientCardDto> list = patientCardMapper.selectEchByOpenId(query.getOpenId());

        return ResultDto.data(list);
    }

    @Override
    public ResultDto addHealthCard(PatientCardAddHeathCardVo vo) {
        //        根据身份证查询 本地 当前患者有没有建档就诊卡信息
        PatientCardEntity entityCertId = new PatientCardEntity();
        entityCertId.setCertId(vo.getCertId());
        List<PatientCardDto> list1 = patientCardMapper.select(entityCertId);
//        根据身份证查询 卫建委 当前有没有健康卡信息
        EHCVo ehcVo = new EHCVo();
        ehcVo.setIdType(vo.getCertType());
        ehcVo.setIdNo(vo.getCertId());
        ehcVo.setPatName(vo.getPatName());
        JSONObject jsonObject = registerEHO(ehcVo);
        Object result = jsonObject.get("result");
        PatientCardEntity entity = JSONCopy.copy(vo, PatientCardEntity.class);
        if (result == null || "".equals(result)) {
            jsonObject.put("error", "电子健康卡 ehc_1001");
//            return ResultDto.data(jsonObject);
        } else {
            JSONObject jsonObject1 = JSONObject.parseObject(result + "");
            entity.setEhcId(jsonObject1.get("ehcId") + "");
            entity.setMindexId(jsonObject1.get("mindexId") + "");
            entity.setQrCodeText(jsonObject1.get("qrCodeText") + "");
        }

        if (list1.size() == 0) {
//            表示当前身份证没有就诊卡信息，需要新建就诊卡，并把当前的健康卡信息一并保存
            entity.setLoginStatus(0);
            patientCardMapper.insert(entity);
        } else {
//            表示当前身份证有就诊卡信息，则查看当前身份证是否有电子健康卡，如果有，则提示已经存在，
//            如果没有，则新增电子健康卡，并返回当前openId下的所有电子健康卡
            entity.setId(list1.get(0).getId());
            patientCardMapper.updateById(entity);
        }

        List<PatientCardDto> list = patientCardMapper.selectEchByOpenId(vo.getOpenId());
        return ResultDto.data(list);
    }

    @Override
    public ResultDto updateHealthInfo(PatientCardVo vo) {
        PatientCardEntity entity = JSONCopy.copy(vo, PatientCardEntity.class);
        return ResultDto.data(patientCardMapper.updateHealthInfo(entity));
    }

    @Override
    public ResultDto patientSelect(PatientSelectQuery query) {
        JSONObject jsonObject = HttpTool.postJson("opt_0001", query);
        Object result = jsonObject.get("result");
        if (result != null && !"[]".equals(result)) {
            List<PatientSelectDto> patientCardEntities = JSONArray.parseArray(result.toString(), PatientSelectDto.class);
            PatientSelectDto dto = patientCardEntities.get(0);
            if (dto != null) {
//                查询当前数据库是否有，如果有，则更新，否则新增
                PatientCardEntity entity = new PatientCardEntity();
                entity.setPatId(dto.getPatId());
                List<PatientCardDto> select = patientCardMapper.select(entity);
                entity.setCaseNo(dto.getCaseNo());
                entity.setPatSex(dto.getPatSex());
                entity.setPatName(dto.getPatName());
                entity.setPatAge(dto.getPatAge());
                entity.setPatBirthDate(dto.getPatBirthDate());
                entity.setNationality(dto.getNationality());
                entity.setNation(dto.getNation());
                entity.setMaritalStatus(dto.getMaritalStatus());
                entity.setBirthPlace(dto.getBirthPlace());
                entity.setRegAddress(dto.getRegAddress());
                entity.setPatAddress(dto.getPatAddress());
                entity.setOccupation(dto.getOccupation());
                entity.setOccupationCode(dto.getOccupationCode());
                entity.setPatPhone(dto.getPatPhone());
                entity.setGuardian(dto.getContacts());
                entity.setGuardianPhone(dto.getContactTel());
                entity.setRelationShip(dto.getContactRel());
                entity.setCertId(dto.getCertId());
                entity.setCardNo(dto.getCardNo());
                if (select.size() > 0) {
                    entity.setId(select.get(0).getId());
                    patientCardMapper.updateById(entity);
                } else {
                    patientCardMapper.insert(entity);
                }
//                将最后患者信息进行查询后返回给前端，可用给前端进行修改
                PatientCardEntity temp = new PatientCardEntity();
                temp.setPatId(dto.getPatId());
                return ResultDto.data(patientCardMapper.select(temp));
            }
            return ResultDto.data(result);
        }
        return ResultDto.data(jsonObject);
    }

    @Override
    public ResultDto add(PatientCardVo patientCardVo) {
        return ResultDto.data(patientCardMapper.insert(JSONCopy.copy(patientCardVo, PatientCardEntity.class)));
    }

    @Override
    public ResultDto update(PatientCardVo patientCardVo) {
//        同时更新到his
        updatePatientToHis(patientCardVo);
        return ResultDto.data(patientCardMapper.updateById(JSONCopy.copy(patientCardVo, PatientCardEntity.class)));
    }

    public void updatePatientToHis(PatientCardVo patientCardVo) {
        JSONObject jsonObject = HttpTool.postJson("opt_0063", patientCardVo);
    }

    @Override
    public ResultDto delete(int id) {
        return ResultDto.data(patientCardMapper.deleteById(id));
    }


    @Override
    public ResultDto status(int id) {
        return ResultDto.data(patientCardMapper.status(id));
    }

    @Override
    public ResultDto loginStatus(Integer loginStatus) {
        return ResultDto.data(patientCardMapper.loginStatus(loginStatus));
    }

    @Override
    public ResultDto updateCampus(PatientCardVo vo) {

        return ResultDto.data(patientCardMapper.updateCampus(JSONCopy.copy(vo, PatientCardEntity.class)));
    }

    @Override
    public ResultDto weChatCode(String code) {
        String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=wxc15843160a0a4020&secret=14ae97605d98c796a2d5130af54ef98e&" +
                "code=" + code + "&grant_type=authorization_code";
        String result = HttpUtil.get(URL);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Object openId = jsonObject.get("openid");
        PatientCardEntity entity = new PatientCardEntity();
        entity.setStatus(1);
        if ("1".equals(code)) {
            entity.setOpenId(defaultOpenId);
        } else {
            if (openId != null) {
                entity.setOpenId(openId.toString());
            }
        }
        return ResultDto.data(patientCardMapper.select(entity));
    }

    @Override
    public ResultDto changeCard(PatientCardChangeVo vo) {
        if (StringUtils.isEmpty(vo.getOldPatId())) {
            return ResultDto.error("请传递当前患者id");
        }

        if (StringUtils.isEmpty(vo.getNewPatId())) {
            return ResultDto.error("请传递需要切换的患者id");
        }
        PatientCardDto oldDto = patientCardMapper.selectByPatId(vo.getOldPatId());
        if (oldDto == null) {
            return ResultDto.error("该患者不存在");
        }
        PatientCardDto newDto = patientCardMapper.selectByPatId(vo.getNewPatId());
        if (newDto == null) {
            return ResultDto.error("该患者不存在");
        }
        if (oldDto.getLoginStatus() == 1) {
            if (newDto.getLoginStatus() == 0) {
                patientCardMapper.loginStatus(oldDto.getId());
                patientCardMapper.loginStatus(newDto.getId());
            }
        }
        return ResultDto.data("success");
    }


    @Override
    public ResultDto record(PatientCardRecordVo vo) {
//        创建建档信息之前，需要将远程his数据导入到本地
        PatientSelectQuery query = new PatientSelectQuery();
        query.setQueryType("4");
        query.setQueryValue(vo.getCertId());
        patientSelect(query);

        EHCVo ehcVo = new EHCVo();
        ehcVo.setIdType(vo.getCertType());
        ehcVo.setIdNo(vo.getCertId());
        ehcVo.setPatName(vo.getPatName());
        JSONObject jsonObject = registerEHO(ehcVo);
        PatientCardEntity entity = JSONCopy.copy(vo, PatientCardEntity.class);
        Object result1 = jsonObject.get("result");
        if (result1 == null || "[]".equals(result1)) {
            jsonObject.put("error", "电子健康卡 ehc_1001");
        } else {
            JSONObject jsonObject1 = JSONObject.parseObject(result1 + "");
            entity.setEhcId(jsonObject1.get("ehcId") + "");
            entity.setMindexId(jsonObject1.get("mindexId") + "");
            entity.setQrCodeText(jsonObject1.get("qrCodeText") + "");
        }

        JSONObject dto = HttpTool.postJson("opt_0020", JSONObject.toJSONString(vo));
//      当建档成功后，需要保存到数据库
        if ("T".equals(dto.get("status"))) {
            if (vo.getOpenId() == null || "".equals(vo.getOpenId())) {
                vo.setOpenId(defaultOpenId);
            }
            JSONObject result = JSONObject.parseObject(dto.get("result") + "");

            Object patId = result.get("patId");
            entity.setStatus(1);
            entity.setCardType(result.get("patCardType") + "");
            entity.setCardNo(result.get("cardNo") + "");
            entity.setCaseNo(result.get("caseNo") + "");
//查询当前openId下的所有数据
            entity.setOpenId(vo.getOpenId());
            //根据openId和身份证查询是否有值
            PatientCardEntity queryEntity = new PatientCardEntity();
            queryEntity.setOpenId(vo.getOpenId());
            queryEntity.setCertId(vo.getCertId());
//
            List<PatientCardDto> list = patientCardMapper.select(queryEntity);

            entity.setPatId(patId + "");

            //遍历里面的数据，如果里面的数据和当前这个身份证一样，则判断当前身份证是否已经创建了电子健康卡
//            如果已经有了，不管他，如果没有则创建电子健康卡
            boolean isHave = false;//默认里面没有数据
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getPatId() != null && list.get(i).getPatId().equals(patId)) {
                    if (list.get(i).getEhcId() == null) {
                        entity.setId(list.get(i).getId());
                        patientCardMapper.updateById(entity);
                    }
                    isHave = true;
                }
            }
//            如果里面没有当前的身份证或者患者id，则直接新增
            if (!isHave) {
                list = patientCardMapper.selectByOpenId(vo.getOpenId());
                entity.setLoginStatus(list.size() > 0 ? 0 : 1);
                patientCardMapper.insert(entity);
            }
            list = patientCardMapper.selectByOpenId(vo.getOpenId());
            return ResultDto.data(list);
        }
        return ResultDto.data(null);
    }

    /**
     * 电子健康卡注册
     *
     * @param vo
     * @return
     */
    private JSONObject registerEHO(EHCVo vo) {
        return HttpTool.postJson("ehc_1001", JSONObject.toJSONString(vo));
    }

}
